import { EventEmitter } from 'stream'
import { WebSocketServer, WebSocket } from 'ws'
import { ApiMsgEnum, IModel } from '../Common'
import { Connection } from './Connection'

// 封装socekt服务
export class MyServer extends EventEmitter {
  port: number
  wss: WebSocketServer
  // 所有客户端连接数组
  connections: Set<any> = new Set() // Set 类数组 成员唯一
  // api接口集合
  apiMap: Map<ApiMsgEnum, Function> = new Map()

  constructor({ port }: { port: number }) {
    super()
    this.port = port
  }

  start() {
    return new Promise((resolve, reject) => {
      this.wss = new WebSocketServer({
        port: 9875,
      })

      this.wss.on('listening', () => {
        resolve(true)
      })
      this.wss.on('close', () => {
        resolve(false)
      })
      this.wss.on('error', error => {
        reject(error)
      })

      this.wss.on('connection', (socket: WebSocket) => {
        // 建立连接并保存
        const connection = new Connection(this, socket)
        this.connections.add(connection)
        this.emit('connection', connection)

        // 断开连接
        connection.on('close', () => {
          this.connections.delete(connection)
          this.emit('disconnection', connection)
        })
      })
    })
  }

  // 建立api
  setApi<T extends keyof IModel['api'] /*泛型约束*/>(name: T, cb: (Connection: Connection, args: IModel['api'][T]['req']) => void) {
    this.apiMap.set(name, cb)
  }
}
